package com.example.ctrip.config;

import com.example.ctrip.commons.Commons;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.io.IOException;


@Component
public class HeaderInterceptor implements ClientHttpRequestInterceptor {
    @Autowired
    private Commons commons;
    @Autowired
    HttpSession httpSession;

    @Override
    public ClientHttpResponse intercept(
            HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {
        String timestamp = String.valueOf(commons.getNowSecondTimestamp());
        HttpHeaders httpHeaders = request.getHeaders();
        httpHeaders.add("X-Auth-Timestamp", timestamp);
        return execution.execute(request, body);
    }


    private String encodePassword(String psw) {
        if (StringUtils.isEmpty(psw)) {
            return null;
        } else {
            return DigestUtils.sha1Hex(psw);
        }
    }
}
